package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.account.service.WalletService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.utils.RandomUtils;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Base64Utils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import wx.wechat.api.API;
import wx.wechat.service.mp.MPService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by neal on 11/17/16.
 */
@RestController
public class APIRewardController extends BaseController {

    @Autowired
    private UserRewardService userRewardService;
    @Autowired
    private WalletCompanyService walletCompanyService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private UserProfitService userProfitService;
    @Autowired
    private WXUserinfoService wxUserinfoService;
    @Autowired
    private CompanyProfitService companyProfitService;
    @Autowired
    private BankCardBagService bankCardBagService;
    @Autowired
    private SysUserService sysUserService;
    /**
     * @api {get} /api/admin/rewards/get 后台管理-订单管理-提现列表
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/rewards/get
     *
     * @apiName findUserRewardPage
     * @apiGroup UserReward
     *
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *               "amount": 100,
     *               "ctime": 1503990774861,
     *               "idCard": "120225198401186013",
     *               "mtime": 1503990867025,
     *               "paymentNo": "1000018301201708299491239664",
     *               "realName": "马英乘",
     *               "remark": "",
     *               "rewardId": 59,
     *               "rewardType": 0,
     *               "rstatus": 1,
     *               "userId": 1
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "title":"成功",
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/rewards/get"
     *  }
     */
    @RequestMapping("/api/admin/rewards/get")
    public String findUserRewardPage(UserReward userReward, int page) {
        userReward.setPage(page);
        if (!ObjectUtils.isEmpty(userReward.getSidx())) {
            userReward.setOrderBy(userReward.getSidx() + " " + userReward.getSord() + "," + userReward.getOrderBy());
        }
        List<UserRewardVO> outList=new ArrayList<>();
        List<UserReward> userRewards=userRewardService.selectForPage(userReward);
        for (UserReward ur:userRewards){
                UserRewardVO userRewardVO=new UserRewardVO();
                BeanUtils.copyProperties(ur, userRewardVO);
                if (ObjectUtils.isEmpty(userRewardVO.getRealName())){
                    userRewardVO.setRealName(sysUserService.selectByPK(userRewardVO.getUserId()).getNickname());
                }
            if (ur.getRewardType() == 1){
                userRewardVO.setCompanyId(companyService.selectByUserId(ur.getUserId()).getCompanyId());
            }
                outList.add(userRewardVO);
        }
        MsgOut o = MsgOut.success(outList);
        o.setRecords(userReward.getRecords());
        o.setTotal(userReward.getTotal());
        return this.renderJson(o);
    }
    @RequestMapping("/api/wap/rewards/get")
    public String wapFindUserReward(Long rewardId,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(rewardId)) {
            return this.renderJson(MsgOut.error("参数错误[rewardId]"));
        }
        HashMap outList = new HashMap();
        UserProfit userProfit = new UserProfit();
        CompanyProfit companyProfit = new CompanyProfit();
        UserReward userReward=userRewardService.selectByPK(rewardId);
        BankCardBag bankCardBag=bankCardBagService.selectByPK(userReward.getBankCardId());
        outList.put("userReward",userReward);
        outList.put("bankCardBag",bankCardBag);
        userProfit.setOrderId(userReward.getRewardId());
        companyProfit.setOrderId(userReward.getRewardId());
        if (userReward.getRstatus()== 0 || userReward.getRstatus() == 1){
            userProfit.setOrderType((byte)-1);
            companyProfit.setOrderType((byte)-1);
        }else {
            userProfit.setOrderType((byte)31);
            companyProfit.setOrderType((byte)31);
        }
        if (userReward.getRewardType() == 0){
            List<UserProfit> userProfits=userProfitService.select(userProfit);
            if (!ObjectUtils.isEmpty(userProfits)){
                outList.put("userProfit",userProfits.get(0));
            }
        }
        if (userReward.getRewardType() == 1){
            List<CompanyProfit> companyProfits = companyProfitService.select(companyProfit);
            if (!ObjectUtils.isEmpty(companyProfits)){
                outList.put("userProfit",companyProfits.get(0));
            }
        }
        MsgOut o = MsgOut.success(outList);
        o.setRecords(userReward.getRecords());
        o.setTotal(userReward.getTotal());
        return this.renderJson(o);
    }
    /**
     * @api {post} /api/admin/rewards/post 后台管理-订单管理-提现列表-创建提现
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/rewards/post
     *
     * @apiName createUserReward
     * @apiGroup UserReward
     *
     * @apiParam {int} amount 第几页.
     * @apiParam {string} idCard 每页条数.
     * @apiParam {string} realName 每页条数.
     * @apiParam {string} remark 每页条数.
     * @apiParam {byte} rewardType 每页条数.
     * @apiParam {byte} rstatus 每页条数.
     * @apiParam {long} userId 每页条数.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *               "amount": 100,
     *               "ctime": 1503990774861,
     *               "idCard": "120225198401186013",
     *               "mtime": 1503990867025,
     *               "paymentNo": "1000018301201708299491239664",
     *               "realName": "马英乘",
     *               "remark": "",
     *               "rewardId": 59,
     *               "rewardType": 0,
     *               "rstatus": 1,
     *               "userId": 1
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "title":"成功",
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/rewards/post"
     *  }
     */
    @RequestMapping(value = "/api/admin/rewards/post", method = RequestMethod.POST)
    public String createUserReward(UserReward userReward) {
        userRewardService.insert(userReward);
        MsgOut o = MsgOut.success(userReward);
        return this.renderJson(o);
    }
    /**
     * @api {put} /api/admin/rewards/put 后台管理-订单管理-修改提现列表
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/rewards/put
     *
     * @apiName createUserReward
     * @apiGroup UserReward
     *
     * @apiParam {int} amount 第几页.
     * @apiParam {string} idCard 每页条数.
     * @apiParam {string} realName 每页条数.
     * @apiParam {string} remark 每页条数.
     * @apiParam {byte} rewardType 每页条数.
     * @apiParam {byte} rstatus 每页条数.
     * @apiParam {long} userId 每页条数.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *               "amount": 100,
     *               "ctime": 1503990774861,
     *               "idCard": "120225198401186013",
     *               "mtime": 1503990867025,
     *               "paymentNo": "1000018301201708299491239664",
     *               "realName": "马英乘",
     *               "remark": "",
     *               "rewardId": 59,
     *               "rewardType": 0,
     *               "rstatus": 1,
     *               "userId": 1
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "title":"成功",
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/rewards/put"
     *  }
     */
    @RequestMapping(value = "/api/admin/rewards/update", method = RequestMethod.PUT)
    public String updateUserReward(UserReward userReward) {
        userRewardService.update(userReward);
        MsgOut o = MsgOut.success(userReward);
        return this.renderJson(o);
    }
    /**
     * @api {delete} /api/admin/rewards/delete/:rewardId 后台管理-订单管理-删除提现
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/rewards/delete/:rewardId
     * @apiPermission admin
     *
     * @apiName deleteGoods
     * @apiGroup Goods
     *
     * @apiParam {long} userRewardId 退货ID
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":1,
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/rewards/delete/:rewardId"
     *  }
     */
    @RequestMapping(value = "/api/admin/rewards/{rewardId}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("rewardId") Long userRewardId) {

        MsgOut o = MsgOut.success(userRewardService.delete(userRewardId));
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/rewards/test")
    public String test() {
        LOGGER.info(" '' {}", this.getClass().getResource(""));
        LOGGER.info(". {}", this.getClass().getResource("."));
        LOGGER.info("/ {}", this.getClass().getResource("/").getPath() + "wxpaycert/apiclient_cert.p12");
        LOGGER.info("user.dir {}", this.getClass().getResource("user.dir"));
        LOGGER.info("user.dir {}", System.getProperty("user.dir"));
        return this.renderJson(MsgOut.success());
    }

    /**
     * 确认提现&提现驳回
     * @param userReward
     * @param type
     * @return
     */
    @RequestMapping(value = "/api/admin/rewards/new", method = RequestMethod.PUT)
    public String adminRewardsUpdate(UserReward userReward,int type){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if(user.getId() != 7 && user.getId() != 17){//caiwu     && user.getId() != 18233
            return this.renderJson(MsgOut.error("你的权限不够。"));
        }
        userReward = userRewardService.selectByPK(userReward.getRewardId());
        //检测余额 是否合理
        if(ObjectUtils.isEmpty(userReward)){
            return this.renderJson(MsgOut.error("参数错误[userReward]"));
        }
        if(ObjectUtils.isEmpty(type) ){
            return this.renderJson(MsgOut.error("参数错误[type]"));
        }
        if(userReward.getRstatus() != 0){
            return this.renderJson(MsgOut.error("记录已经审核过，请误重复提交"));
        }
        //已经付过款
        if (type == 2){
            if(userReward.getRstatus()!=1){
                userReward.setRstatus((byte)1);
                userReward.setRemark(user.getNickname());
                userRewardService.update(userReward);
            }
        }
        if (type == 3){
            if(userReward.getRstatus()!=2){
                userReward.setRstatus((byte)2);
                userReward.setRemark(user.getNickname());
                userRewardService.update(userReward);
            }
            //用户提现
            if (userReward.getRewardType() == 0){
                UserProfit userProfit = new UserProfit();
                userProfit.setOrderId(userReward.getRewardId());
                userProfit.setOrderType((byte)-1);
                List<UserProfit> userProfits=userProfitService.select(userProfit);
                if (!ObjectUtils.isEmpty(userProfits)){
                    Wallet wallet=walletService.selectByPK(userReward.getUserId());
                    userProfit.setUserBalance(wallet.getUserBalance() + userReward.getAmount());
                    userProfit=userProfits.get(0);
                    userProfit.setOrderType((byte)31);
                    userProfitService.insert(userProfit);
                    //增加个人钱包的扣除的金额

                    wallet.setUserBalance(wallet.getUserBalance() + userReward.getAmount());
                    walletService.update(wallet);
                }else {
                    return this.renderJson(MsgOut.error("无扣除金额流水记录"));
                }
            }
            //商家提现
            if (userReward.getRewardType() == 1){
                CompanyProfit companyProfit= new CompanyProfit();
                companyProfit.setOrderId(userReward.getRewardId());
                companyProfit.setOrderType((byte)-1);
                List<CompanyProfit> companyProfits=companyProfitService.select(companyProfit);
                if (!ObjectUtils.isEmpty(companyProfits)){
                    WalletCompany walletCompany=walletCompanyService.selectByPK(companyService.selectByUserId(userReward.getUserId()).getCompanyId());
                    companyProfit=companyProfits.get(0);
                    companyProfit.setCompanyBalance(walletCompany.getCompanyBalance() + userReward.getAmount());
                    companyProfit.setOrderType((byte)31);
                    companyProfitService.insert(companyProfit);
                    //增加商家钱包的金额

                    walletCompany.setCompanyBalance(walletCompany.getCompanyBalance() + userReward.getAmount());
                    walletCompanyService.update(walletCompany);
                }else {
                    return this.renderJson(MsgOut.error("无扣除金额流水记录"));
                }
            }
        }
        userRewardService.update(userReward);
        return this.renderJson(MsgOut.success(userReward));
    }
    @RequestMapping(value = "/api/admin/rewards", method = RequestMethod.PUT)
    public String update(UserReward userReward) throws Exception {

        SysUser user = LYSecurityUtil.currentSysUser();
        if(user.getId() != 7 && user.getId() != 17){//caiwu && user.getId() != 18233
            return this.renderJson(MsgOut.error("你的权限不够。"));
        }
        userReward = userRewardService.selectByPK(userReward.getRewardId());
        //检测余额 是否合理
        if(ObjectUtils.isEmpty(userReward) ){
            return this.renderJson(MsgOut.error("数据不正常"));
        }
        //已经付过款
        if(userReward.getRstatus()==1){
            return this.renderJson(MsgOut.error("已经付过款"));
        }
        String openid = "";
        String certPath = this.getClass().getResource("/").getPath() + "wxpaycert/apiclient_cert.p12";

        Long userId = userReward.getUserId();
        if(userReward.getRewardType() == 0){//个人帐户
            Wallet wallet = walletService.selectByPK(userId);
            if(!ObjectUtils.isEmpty(wallet)) {

                //企业自动付款
                MPService mpService = new MPService();
                SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK(userReward.getUserId());
                openid = snswxUserinfo.getOpenid();
                Map<String, Object> rs = null;
                try {
                    rs = mpService.transfers("" + userReward.getRewardId(), openid, userReward.getAmount(), API.getClientIpAddress(this.getRequest()), certPath);
                    LOGGER.debug("transfers rs : {}", rs);
                } catch (Exception e) {
                    return this.renderJson(MsgOut.error("微信支付异常."));
                }
//                postByXMLForSSL : <xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[支付失败]]></return_msg><mch_appid><![CDATA[wx488ae3f57360b7ea]]></mch_appid><mchid><![CDATA[1227170502]]></mchid><result_code><![CDATA[FAIL]]></result_code><err_code><![CDATA[NOTENOUGH]]></err_code><err_code_des><![CDATA[余额不足]]></err_code_des></xml>

                if(ObjectUtils.isEmpty(rs) || ObjectUtils.isEmpty(rs.get("payment_no"))){
                    return this.renderJson(MsgOut.error("微信支付异常: " + rs.get("return_msg")));
                }
                if ("SUCCESS".equals(rs.get("return_code").toString())) {
                    userReward.setRemark(rs.get("return_msg").toString());
                    userReward.setPaymentNo(rs.get("payment_no").toString());
                } else {
                    userReward.setRemark(rs.get("return_msg").toString());
                }

                //减去 现在帐户余额 - 提现金额
//                wallet.setUserBalance(wallet.getUserBalance() - userReward.getAmount());
//                walletService.update(wallet);
                userReward.setRstatus((byte) 1);//已提现
//                userRewardService.update(userReward);
//                //TODO: transaction 个人钱包支出一笔
//                UserProfit userProfit = new UserProfit();
//                userProfit.setOrderSn("-1");
//                userProfit.setUserId(userId);
//                userProfit.setOrderType((byte) -1);
//                userProfit.setUserProfit(-userReward.getAmount());
//                userProfit.setAmount(userReward.getAmount());
//                userProfitService.insert(userProfit);

                userRewardService.update(userReward);
                return this.renderJson(MsgOut.success(userReward));
            }
        }

        if(userReward.getRewardType() == 1){//微商帐户
            Company company = companyService.selectMicroUserByUserId(userId);
            if (!ObjectUtils.isEmpty(company)) {
                WalletCompany walletCompany = walletCompanyService.selectByPK(company.getCompanyId());
                if (!ObjectUtils.isEmpty(walletCompany)) {

                    //企业自动付款
                    MPService mpService = new MPService();
                    SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK(userReward.getUserId());
                    openid = snswxUserinfo.getOpenid();
                    Map<String, Object> rs = null;
                    try {
                        rs = mpService.transfers("" + userReward.getRewardId(), openid, userReward.getAmount(), API.getClientIpAddress(this.getRequest()), certPath);
                        LOGGER.debug("transfers rs : {}", rs);
                    } catch (Exception e) {
                        return this.renderJson(MsgOut.error("微信支付异常."));
                    }
                    if(ObjectUtils.isEmpty(rs) || ObjectUtils.isEmpty(rs.get("payment_no"))){
                        return this.renderJson(MsgOut.error("微信支付异常: " + rs.get("return_msg")));
                    }
                    if ("SUCCESS".equals(rs.get("return_code").toString())) {
                        userReward.setRemark(rs.get("return_msg").toString());
                        userReward.setPaymentNo(rs.get("payment_no").toString());
                    } else {
                        userReward.setRemark(rs.get("return_msg").toString());
                    }

//                    walletCompany.setCompanyBalance(walletCompany.getCompanyBalance() - userReward.getAmount());
//                    walletCompanyService.update(walletCompany);
                    userReward.setRstatus((byte) 1);//已提现
//                    userRewardService.update(userReward);
//                    //TODO: transaction 公司钱包支出一笔
//                    UserProfit userProfit = new UserProfit();
//                    userProfit.setOrderSn("-1");
//                    userProfit.setUserId(company.getUserId());//user id
//                    userProfit.setOrderType((byte) -1);
//                    userProfit.setRemark(userId.toString());//company id
//                    userProfit.setUserProfit(-userReward.getAmount());
//                    userProfit.setAmount(userReward.getAmount());
//                    userProfitService.insert(userProfit);


                    userRewardService.update(userReward);
                    return this.renderJson(MsgOut.success(userReward));
                }
            }
        }
        if(userReward.getRewardType() == 10){//点餐帐户
            Company company = companyService.selectDinnerByUserId(userId);
            if (!ObjectUtils.isEmpty(company)) {
                WalletCompany walletCompany = walletCompanyService.selectByPK(company.getCompanyId());
                if (!ObjectUtils.isEmpty(walletCompany)) {

                    //企业自动付款
                    MPService mpService = new MPService();
                    SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK(userReward.getUserId());
                    openid = snswxUserinfo.getOpenid();
                    Map<String, Object> rs = null;
                    try {
                        rs = mpService.transfers("" + userReward.getRewardId(), openid, userReward.getAmount(), API.getClientIpAddress(this.getRequest()), certPath);
                        LOGGER.debug("transfers rs : {}", rs);
                    } catch (Exception e) {
                        return this.renderJson(MsgOut.error("微信支付异常."));
                    }
                    if(ObjectUtils.isEmpty(rs) || ObjectUtils.isEmpty(rs.get("payment_no"))){
                        return this.renderJson(MsgOut.error("微信支付异常: " + rs.get("return_msg")));
                    }
                    if ("SUCCESS".equals(rs.get("return_code").toString())) {
                        userReward.setRemark(rs.get("return_msg").toString());
                        userReward.setPaymentNo(rs.get("payment_no").toString());
                    } else {
                        userReward.setRemark(rs.get("return_msg").toString());
                    }

//                    walletCompany.setCompanyBalance(walletCompany.getCompanyBalance() - userReward.getAmount());
//                    walletCompanyService.update(walletCompany);
                    userReward.setRstatus((byte) 1);//已提现
//                    userRewardService.update(userReward);
//                    //TODO: transaction 公司钱包支出一笔
//                    UserProfit userProfit = new UserProfit();
//                    userProfit.setOrderSn("-1");
//                    userProfit.setUserId(company.getUserId());//user id
//                    userProfit.setOrderType((byte) -1);
//                    userProfit.setRemark(userId.toString());//company id
//                    userProfit.setUserProfit(-userReward.getAmount());
//                    userProfit.setAmount(userReward.getAmount());
//                    userProfitService.insert(userProfit);


                    userRewardService.update(userReward);
                    return this.renderJson(MsgOut.success(userReward));
                }
            }
        }
        if(userReward.getRewardType() == 11){//互动商家帐户
            Company company = companyService.selectInteractionByUserId(userId);
            if (!ObjectUtils.isEmpty(company)) {
                WalletCompany walletCompany = walletCompanyService.selectByPK(company.getCompanyId());
                if (!ObjectUtils.isEmpty(walletCompany)) {

                    //企业自动付款
                    MPService mpService = new MPService();
                    SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK(userReward.getUserId());
                    openid = snswxUserinfo.getOpenid();
                    Map<String, Object> rs = null;
                    try {
                        rs = mpService.transfers("" + userReward.getRewardId(), openid, userReward.getAmount(), API.getClientIpAddress(this.getRequest()), certPath);
                        LOGGER.debug("transfers rs : {}", rs);
                    } catch (Exception e) {
                        return this.renderJson(MsgOut.error("微信支付异常."));
                    }
                    if(ObjectUtils.isEmpty(rs) || ObjectUtils.isEmpty(rs.get("payment_no"))){
                        return this.renderJson(MsgOut.error("微信支付异常: " + rs.get("return_msg")));
                    }
                    if ("SUCCESS".equals(rs.get("return_code").toString())) {
                        userReward.setRemark(rs.get("return_msg").toString());
                        userReward.setPaymentNo(rs.get("payment_no").toString());
                    } else {
                        userReward.setRemark(rs.get("return_msg").toString());
                    }

//                    walletCompany.setCompanyBalance(walletCompany.getCompanyBalance() - userReward.getAmount());
//                    walletCompanyService.update(walletCompany);
                    userReward.setRstatus((byte) 1);//已提现
//                    userRewardService.update(userReward);
//                    //TODO: transaction 公司钱包支出一笔
//                    UserProfit userProfit = new UserProfit();
//                    userProfit.setOrderSn("-1");
//                    userProfit.setUserId(company.getUserId());//user id
//                    userProfit.setOrderType((byte) -1);
//                    userProfit.setRemark(userId.toString());//company id
//                    userProfit.setUserProfit(-userReward.getAmount());
//                    userProfit.setAmount(userReward.getAmount());
//                    userProfitService.insert(userProfit);


                    userRewardService.update(userReward);
                    return this.renderJson(MsgOut.success(userReward));
                }
            }
        }
        return this.renderJson(MsgOut.error("数据不正常"));
    }

    /**
     * 提现到银行卡
     * @param userReward
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/api/admin/rewardsToBank", method = RequestMethod.PUT)
    public String rewardsToBank(UserReward userReward,BankCardBag bankCardBag) throws Exception {

        SysUser user = LYSecurityUtil.currentSysUser();
//        if(user.getId() != 7 && user.getId() != 17){//caiwu && user.getId() != 18233
//            return this.renderJson(MsgOut.error("你的权限不够。"));
//        }
        userReward = userRewardService.selectByPK(userReward.getRewardId());
        bankCardBag = bankCardBagService.selectByPK(bankCardBag.getId());
        //检测余额 是否合理
        if(ObjectUtils.isEmpty(userReward) ){
            return this.renderJson(MsgOut.error("数据不正常"));
        }
        //已经付过款
        if(userReward.getRstatus()==1){
            return this.renderJson(MsgOut.error("已经付过款"));
        }
        String certPath = this.getClass().getResource("/").getPath() + "wxpaycert/apiclient_cert.p12";
        Long userId = userReward.getUserId();
        if(userReward.getRewardType() == 0){//个人帐户
            Wallet wallet = walletService.selectByPK(userId);
            if(!ObjectUtils.isEmpty(wallet)) {
                //企业自动付款
                MPService mpService = new MPService();
                Map<String, Object> rs;
                try {
                    rs = mpService.payToBank("" + userReward.getRewardId(), userReward.getAmount(),certPath,bankCardBag);
                    LOGGER.debug("transfers rs : {}", rs);
                } catch (Exception e) {
                    return this.renderJson(MsgOut.error("支付异常."));
                }
                if(ObjectUtils.isEmpty(rs) || ObjectUtils.isEmpty(rs.get("payment_no"))){
                    return this.renderJson(MsgOut.error("微信支付异常: " + rs.get("return_msg")));
                }
                if ("SUCCESS".equals(rs.get("return_code").toString())) {
                    userReward.setRemark(rs.get("return_msg").toString());
                    userReward.setPaymentNo(rs.get("payment_no").toString());
                } else {
                    userReward.setRemark(rs.get("return_msg").toString());
                }
                userReward.setRstatus((byte) 1);//已提现
                userRewardService.update(userReward);
                return this.renderJson(MsgOut.success(userReward));
            }
        }

        if(userReward.getRewardType() == 1){//微商帐户
            Company company = companyService.selectMicroUserByUserId(userId);
            if (!ObjectUtils.isEmpty(company)) {
                WalletCompany walletCompany = walletCompanyService.selectByPK(company.getCompanyId());
                if (!ObjectUtils.isEmpty(walletCompany)) {
                    //企业自动付款
                    MPService mpService = new MPService();
                    Map<String, Object> rs;
                    try {
                        rs = mpService.payToBank("" + userReward.getRewardId(), userReward.getAmount(),certPath,bankCardBag);
                        LOGGER.debug("transfers rs : {}", rs);
                    } catch (Exception e) {
                        return this.renderJson(MsgOut.error("微信支付异常."));
                    }
                    if(ObjectUtils.isEmpty(rs) || ObjectUtils.isEmpty(rs.get("payment_no"))){
                        return this.renderJson(MsgOut.error("微信支付异常: " + rs.get("return_msg")));
                    }
                    if ("SUCCESS".equals(rs.get("return_code").toString())) {
                        userReward.setRemark(rs.get("return_msg").toString());
                        userReward.setPaymentNo(rs.get("payment_no").toString());
                    } else {
                        userReward.setRemark(rs.get("return_msg").toString());
                    }
                    userReward.setRstatus((byte) 1);//已提现
                    userRewardService.update(userReward);
                    return this.renderJson(MsgOut.success(userReward));
                }
            }
        }
        if(userReward.getRewardType() == 10){//点餐帐户
            Company company = companyService.selectDinnerByUserId(userId);
            if (!ObjectUtils.isEmpty(company)) {
                WalletCompany walletCompany = walletCompanyService.selectByPK(company.getCompanyId());
                if (!ObjectUtils.isEmpty(walletCompany)) {
                    //企业自动付款
                    MPService mpService = new MPService();
                    Map<String, Object> rs;
                    try {
                        rs = mpService.payToBank("" + userReward.getRewardId(), userReward.getAmount(),certPath,bankCardBag);
                        LOGGER.debug("transfers rs : {}", rs);
                    } catch (Exception e) {
                        return this.renderJson(MsgOut.error("微信支付异常."));
                    }
                    if(ObjectUtils.isEmpty(rs) || ObjectUtils.isEmpty(rs.get("payment_no"))){
                        return this.renderJson(MsgOut.error("微信支付异常: " + rs.get("return_msg")));
                    }
                    if ("SUCCESS".equals(rs.get("return_code").toString())) {
                        userReward.setRemark(rs.get("return_msg").toString());
                        userReward.setPaymentNo(rs.get("payment_no").toString());
                    } else {
                        userReward.setRemark(rs.get("return_msg").toString());
                    }
                    userReward.setRstatus((byte) 1);//已提现
                    userRewardService.update(userReward);
                    return this.renderJson(MsgOut.success(userReward));
                }
            }
        }
        if(userReward.getRewardType() == 11){//互动商家帐户
            Company company = companyService.selectInteractionByUserId(userId);
            if (!ObjectUtils.isEmpty(company)) {
                WalletCompany walletCompany = walletCompanyService.selectByPK(company.getCompanyId());
                if (!ObjectUtils.isEmpty(walletCompany)) {

                    //企业自动付款
                    MPService mpService = new MPService();
                    Map<String, Object> rs;
                    try {
                        rs = mpService.payToBank("" + userReward.getRewardId(), userReward.getAmount(),certPath,bankCardBag);
                        LOGGER.debug("transfers rs : {}", rs);
                    } catch (Exception e) {
                        return this.renderJson(MsgOut.error("微信支付异常."));
                    }
                    if(ObjectUtils.isEmpty(rs) || ObjectUtils.isEmpty(rs.get("payment_no"))){
                        return this.renderJson(MsgOut.error("微信支付异常: " + rs.get("return_msg")));
                    }
                    if ("SUCCESS".equals(rs.get("return_code").toString())) {
                        userReward.setRemark(rs.get("return_msg").toString());
                        userReward.setPaymentNo(rs.get("payment_no").toString());
                    } else {
                        userReward.setRemark(rs.get("return_msg").toString());
                    }
                    userReward.setRstatus((byte) 1);//已提现
                    userRewardService.update(userReward);
                    return this.renderJson(MsgOut.success(userReward));
                }
            }
        }
        return this.renderJson(MsgOut.error("数据不正常"));
    }
}
